import React, { forwardRef, useImperativeHandle, useState } from 'react';
import _ from 'lodash';
import { Button, Form, Input, message, notification } from 'antd';
import DebounceWrapper from '@/components/DebounceWrapper';
import { ArrowLeftOutlined, PhoneOutlined, SafetyOutlined } from '@ant-design/icons';
import { validatePhone } from '@/utils/validate';
import { sendPhoneValidCode } from '@/services/common';
import styles from './loginForm.less';

const limitCountDown = 60;
const DebounceButton = DebounceWrapper(Button);

export default forwardRef(({ loginLoading, loginDisabled, handleLogin, turnBack }, ref) => {
  const [form] = Form.useForm();
  const [sendLoading, setSendLoading] = useState(false);
  const [countDown, setCountDown] = useState(0);

  // 发送验证码
  const startCountDown = () => {
    setCountDown(limitCountDown);
    const timer = setInterval(() => {
      setCountDown((currentNum) => {
        if (currentNum) {
          const nextNum = currentNum - 1;
          if (!nextNum) {
            clearInterval(timer);
          }
          return nextNum;
        } else {
          clearInterval(timer);
        }
      });
    }, 1000);
  };
  const handleSendCode = () => {
    form
      .validateFields(['phone'])
      .then((values) => {
        setSendLoading(true);
        form.setFields([{ name: 'code', value: '', errors: [] }]);
        sendPhoneValidCode(values)
          .then((res) => {
            startCountDown();
            setSendLoading(false);
            if (process?.env?.NODE_ENV === 'development') {
              const { code } = _.isPlainObject(res) ? res : {};
              if (/^\d+$/.test(code)) {
                form.setFields([{ name: 'code', value: code, errors: [] }]);
                notification.success({
                  message: '请求成功',
                  description: `验证码发送成功：${code}`,
                });
              }
            }
          })
          .catch(() => {
            setSendLoading(false);
          });
      })
      .catch(() => {
        message.warning('请输入有效的手机号');
      });
  };

  // 方法挂载
  useImperativeHandle(ref, () => ({
    errorHandle: ({ code, description }) => {
      const currentCode = form.getFieldValue('code');
      const currentPhone = form.getFieldValue('phone');
      switch (code) {
        case 100008:
          form.setFields([
            { name: 'code', value: currentCode, errors: [description || '验证码无效'] },
          ]);
          break;
        case 100009:
          form.setFields([
            { name: 'code', value: currentCode, errors: [description || '验证码有误'] },
          ]);
          break;
        case 100010:
          form.setFields([
            { name: 'code', value: '', errors: [] },
            { name: 'phone', value: currentPhone, errors: [description || '账号有误或无效'] },
          ]);
          break;
        default:
          form.setFields([{ name: 'code', value: '', errors: [] }]);
          break;
      }
    },
  }));

  // 登录
  const handleLoginClick = () => {
    form.validateFields().then((values) => {
      handleLogin(values);
    });
  };

  // 返回账号登录
  const ReturnBack = DebounceWrapper(() => (
    <div
      title={'返回账号登录'}
      className={styles.loginFormBackHandle}
      style={{ cursor: !loginLoading ? 'pointer' : 'not-allowed' }}
      onClick={() => {
        if (!loginLoading) {
          turnBack && turnBack();
        }
      }}
    >
      <ArrowLeftOutlined className={styles.loginFormBackHandleIcon} />
      <span className={styles.loginFormBackHandleText}>返回</span>
    </div>
  ));

  return (
    <div className={styles.formContent}>
      <div className={styles.loginFormTitle}>
        <ReturnBack />
        手机号登录
      </div>
      <div className={styles.loginFormCube}>
        <Form name="phone-login" form={form}>
          <div className={styles.loginFormItem}>
            <span className={styles.loginFormLabelIcon}>
              <PhoneOutlined className={styles.loginIcon} />
            </span>
            <Form.Item
              name="phone"
              label={<PhoneOutlined className={styles.loginIcon} />}
              rules={[
                { required: true, message: '请输入手机号' },
                {
                  validator: (rule, val) => {
                    if (val) {
                      if (validatePhone(val)) {
                        return Promise.resolve();
                      } else {
                        return Promise.reject(new Error('手机号格式有误'));
                      }
                    } else {
                      return Promise.resolve();
                    }
                  },
                },
              ]}
            >
              <Input placeholder="请输入手机号" maxLength={11} autoComplete="off" />
            </Form.Item>
          </div>

          <div className={styles.loginFormItem}>
            <span className={styles.loginFormLabelIcon}>
              <SafetyOutlined className={styles.loginIcon} />
            </span>
            <Form.Item
              name="code"
              label={<SafetyOutlined className={styles.loginIcon} />}
              className={styles.loginFormValidateControl}
              rules={[{ required: true, whitespace: true, message: '请输入短信验证码' }]}
            >
              <Input placeholder="验证码" maxLength={4} autoComplete="off" />
            </Form.Item>
            <div className={styles.loginFormSendCode}>
              <DebounceButton
                type="primary"
                loading={sendLoading}
                onClick={() => {
                  if (!countDown && !loginLoading) {
                    handleSendCode();
                  }
                }}
              >
                {countDown ? `${countDown} 秒` : '获取验证码'}
              </DebounceButton>
            </div>
          </div>

          <DebounceButton
            block
            htmlType="submit"
            type="primary"
            loading={loginLoading}
            onClick={() => {
              if (!loginDisabled) {
                handleLoginClick();
              }
            }}
          >
            登录
          </DebounceButton>
        </Form>
      </div>
    </div>
  );
});
